// 封装分类目录相关代码
import { useRouter } from 'vue-router'
import { onMounted, ref } from 'vue'
import { getCategoryAPI } from '@/apis/category.js'
import { onBeforeRouteUpdate } from 'vue-router'

export function useCategory() { 
    // 获取router实例对象
    const route = useRouter()

    // 获取数据
    const categoryData = ref({})
    const getCategory = async (id = route.params.id) => {
    const res = await getCategoryAPI(id)
        categoryData.value = res.result
    }

    onMounted(() => {
        getCategory()
    })

    // 在路由参数变化时,可以把分类接口重新发送
    onBeforeRouteUpdate((to) => {
        console.log("路由变化")
        // 获取最新的路由参数
        getCategory(to.params.id)
    })

    return {
        categoryData
    }
}